<template>
  <a-modal
    title="申请样品"
    :width="660"
    :visible="visible"
    @ok="handleModalConfirm"
    @cancel="handleModalCancel"
    :confirm-loading="modalLoading"
    @after-open="saveFocusedElement"
    @after-close="restoreFocusedElement"
  >
    <a-form-model
      ref="form"
      :model="form"
      :rules="formRules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <a-form-model-item label="产品信息">
        <div class="product_information">
          <img :src="product_info.image" alt="" />
          <div class="product_info">
            <div class="product_name">{{ product_info.title }}</div>
            <div class="product_price">
              <p>
                <span>¥</span><span>{{ product_info.price[0] }}</span>
              </p>
              <p>库存：{{ product_info.stock }}件</p>
            </div>
          </div>
        </div>
      </a-form-model-item>
      <a-form-model-item label="申样数量" prop="quantity">
        <div class="input_box">
          <div class="minus_btn" @click="form.quantity--">-</div>
          <a-input-number
            id="quantity"
            v-model="form.quantity"
            :min="1"
            :max="100"
            @change="onChange"
          />
          <div class="add_btn" @click="form.quantity++">+</div>
        </div>
      </a-form-model-item>
      <a-form-model-item label="选择达人" prop="master">
        <a-select
          v-model="form.master"
          :get-popup-container="getPopupContainer"
          @popupScroll="handlePopupScroll"
          placeholder="请选择达人"
          @change="handleSelectChange"
           v-if="customersListOptions.length > 0"
        >
          <a-select-option
            v-for="user in customersListOptions"
            :key="user.id"
            :value="user.id"
          >
            <div style="display: flex; align-items: center">
              <img
                :src="
                  user.portrait
                    ? processImage(user.portrait)
                    : processImage(
                        '/storage/app_icon/20241115/8db41e60976fb7f1210af4e19c2122cb.png'
                      )
                "
                alt="avatar"
                style="
                  width: 30px;
                  height: 30px;
                  margin-right: 8px;
                  border-radius: 50%;
                "
              />
              <span class="nickname">{{ user.nickname }}</span> (ID:
              {{ user.ks_user_id }})
              <span class="delivery_rate"
                >申样交付率: {{ user.delivery_rate }}%</span
              >
            </div>
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="收获地址" prop="address_id" class="address_box">
        <div style="display: flex; align-items: center; margin-top: 4px">
          <a-select
            v-model="form.address_id"
            :get-popup-container="getPopupContainer"
            @popupScroll="handlePopupScroll"
            placeholder="请选择达人收货地址"
            @change="addressChange"
             v-if="addressOptions.length > 0"
          >
            <a-select-option
              v-for="option in addressOptions"
              :key="option.id"
              :value="option.id"
            >
              <div>
                <div>{{ option.consignee }} {{ option.mobile }}</div>
                <div>
                  {{ option.province_name }} {{ option.city_name}}
                  {{ option.district_name }} {{ option.address }}
                </div>
              </div>
            </a-select-option>
          </a-select>
          <div class="address_btn" v-if="form.master" @click="addAddress">添加地址</div>
        </div>
      </a-form-model-item>

      <a-form-model-item label="配送方式" prop="distributionMode">
        <a-input
          style="width: 200px"
          v-model="form.distributionMode"
          allowClear
          disabled
        />
      </a-form-model-item>
      <a-form-model-item label="是否发货" prop="normal_special">
        <a-radio-group v-model="form.normal_special">
          <a-radio
            v-for="(item, index) in plainOptions"
            :key="index"
            :value="item.productId"
            >{{ item.productName }}</a-radio
          >
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="属性链接" prop="link_property" class="link_box">
        <a-radio-group v-model="form.link_property">
          <div style="display: flex; align-items: center; margin-top: 4px">
            <div
              class="link_item"
              v-for="(item, index) in statsLink"
              :key="index"
            >
              <a-radio :value="item.linkStats">{{ item.linkName }} </a-radio>
              <!-- <img src="../../assets/img/login/icon_qu.png" alt=""> -->
            </div>
          </div>
          <div class="link_desc" v-if="form.link_property == 1">
            所有达人都可以带货
          </div>
          <div class="link_desc" v-else-if="form.link_property == 2">
            只有被指定达人可以带货
          </div>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="商品前缀" prop="product_prefix">
        <a-input
          v-model="form.product_prefix"
          placeholder="请输入"
          allowClear
        />
      </a-form-model-item>
      <a-form-model-item label="订单备注" prop="remark">
        <a-textarea
          v-model="form.remark"
          placeholder="请输入"
          :auto-size="{ minRows: 3, maxRows: 3 }"
        />
      </a-form-model-item>

      <div class="tips_content" v-if="product_info">
        <div class="title">*免费申样条件：</div>
        <div class="cont_text">
          粉丝数≥{{ product_info?.fans / 10000 }}万 30天橱窗销售量≥{{
            product_info?.thirty_sales_volume
          }}
          30天橱窗销售额≥{{ product_info?.thirty_sales_money / 10000 }}万
        </div>
      </div>
    </a-form-model>
    <a-modal
      v-model="visibleAddress"
      title="添加收货信息"
      @ok="handleOkAddress"
      @cancel="handleModalCancelAddress"
    >
      <a-form-model
        ref="form2"
        :model="form2"
        :rules="formRules2"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <!-- <a-form-model-item label="智能识别" prop="consignee">
          <a-textarea
            v-model="form.intelligent"
            placeholder="请输入"
            :auto-size="{ minRows: 3, maxRows: 3 }"
          />
          <a-button type="primary" @click="handleOkAddress">一键识别</a-button>
        </a-form-model-item> -->
        <a-form-model-item label="收货人" prop="consignee">
          <a-input v-model="form2.consignee" placeholder="请输入" allowClear />
        </a-form-model-item>
        <a-form-model-item label="手机号码" prop="mobile">
          <a-input v-model="form2.mobile" placeholder="请输入" allowClear  />
        </a-form-model-item>
        <a-form-model-item label="所在地区" prop="province_name">
          <area-select
            @change="selectArea"
            :default-value="form2.defaultArea"
          />
          
        </a-form-model-item>
        <a-form-model-item label="详细地址" prop="address">
          <a-textarea
            v-model="form2.address"
            placeholder="请输入"
            :auto-size="{ minRows: 3, maxRows: 3 }"
          />
        </a-form-model-item>
        <a-form-model-item label="默认地址">
          <a-switch v-model="form2.is_default" checked-children="开启" un-checked-children="关闭" style="margin-left: 10px;" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-modal>
</template>

<script>
import * as Ajax from "@/api/channel";
import areaSelect from "./areaselect";
import areaData from "./areaData";
import { mapState, mapGetters } from "vuex";
export default {
  props: {
    task_uuid: {
      type: String,
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    detailsInfo: {
      type: Object,
      default: () => ({}),
    },
    
  },

  components: {
    areaSelect,
  },
  data() {
    return {
      modalLoading: false,
      form: {
        quantity: 1,
        master: "",
        address_id: "",
        distributionMode: "快递物流",
        normal_special: null,
        link_property: null,
        product_prefix: "",
        remark: "",
        goods_no: "",
        ks_user_id: "",
        apply_commission_rate: "",
        apply_service_rate: "",
        promotion_money_rate: "",
        institution_uuid: "",
        task_uuid: "",
      },
      formRules: {
        distributionMode: {
          required: true,
          message: "请输入公司名称",
          trigger: ["blur", "change"],
        },
        quantity: {
          required: true,
          message: "请输入价格",
          trigger: ["blur", "change"],
        },
        address_id: {
          required: true,
          message: "请选择地址",
          trigger: ["blur", "change"],
        },
        master: {
          required: true,
          message: "请选择达人",
          trigger: ["blur", "change"],
        },
        normal_special: [
          { required: true, message: "请选择是否发货", trigger: "change" },
        ],
        link_property: [
          { required: true, message: "请选择属性链接", trigger: "change" },
        ],
        product_prefix: {
          required: true,
          message: "请输入商品前缀",
          trigger: ["blur", "change"],
        },
        remark: {
          required: true,
          message: "请输入订单备注",
          trigger: ["blur", "change"],
        },
      },
      form2: {
        consignee: "",
        mobile: "",
        province_name: "",
        city_name: "",
        district_name: "",
        address: "",
        defaultArea: [],
        is_default: false,
        promotionId: null,
        institution_uuid: null,
      },
      formRules2: {
      // 其他规则
      consignee: [
        { required: true, message: '请输入收货人', trigger: 'blur' },
      ],
      mobile: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' },
      ],
      province_name: [
        { required: true, message: '请选择所在地区', trigger: 'change' },
      ],
      address: [
        { required: true, message: '请输入详细地址', trigger: 'blur' },
      ],
    },
      typeOptions: [
        { label: "同业", value: 0 },
        { label: "信息流", value: 1 },
      ],
      addressOptions: [],
      focusedElement: null,
      testInfo: {
        order_count: "",
        commission: "",
        commission2: "",
      },
      tipShow: false,
      page: 1,
      customersListOptions: [],
      noMoreData: false,
      loadStatus: "加载更多",
      promotionId: null,
      institution_uuid: null,
      plainOptions: [
        {
          productId: 1,
          productName: "是",
        },
        {
          productId: 2,
          productName: "否",
        },
      ],
      statsLink: [
        {
          linkStats: 1,
          linkName: "公开",
        },
        {
          linkStats: 2,
          linkName: "专属",
        },
      ],
      product_info: {},
      visibleAddress: false,
      defaultArea: [],
      areaData,
      good_ID: "",
    };
  },
  computed: {
    ...mapGetters("user", ["getCdnUrl", "getUserInfo"]),
  },
  methods: {
    processImage(imageUrl) {
      if (imageUrl === undefined || imageUrl === null) {
        return ""; // 或者返回一个默认的 URL
      }

      if (!imageUrl.startsWith("http")) {
        return this.getCdnUrl + imageUrl;
      }
      return imageUrl;
    },
    handleModalConfirm() {
      this.$refs.form.validate((valid) => {
        console.log("valid", this.form);
        
        if (valid) {
          console.log("确定提交");
          this.samplesAdd();
        } else {
          console.log("表单验证失败");
        }
      });
    },
    get_receiveEstimate() {
      Ajax.receiveEstimate({
        sale_money: this.form.channelName,
        task_uuid: this.task_uuid,
      }).then((res) => {
        console.log("res.error", res.error);

        if (res.error === 0) {
          this.testInfo.commission = res.data.commission;
          this.testInfo.commission2 =
            (res.data.commission - 0) /
            (this.level_task_commission_rate - 0 * 0.01);
          this.testInfo.order_count = res.data.order_count;
          this.tipShow = true;
        }
      });
    },
    handleModalCancel() {
      // this.form = this.$options.data().form;
      console.log("取消提交",this.form);
      const oldForm = this.form
      this.form = oldForm
      this.$refs.form.resetFields();
      this.$emit("close");
    },
    saveFocusedElement() {
      this.focusedElement = document.activeElement;
    },
    restoreFocusedElement() {
      if (this.focusedElement) {
        this.focusedElement.focus();
      }
    },
    handleChange() {
      this.get_receiveEstimate();
    },
    onChange(value) {
      console.log("changed", value);
    },
    handleChange2(value) {
      console.log(`selected ${value}`);
    },
    get_customersList() {
      Ajax.customersList({
        page: this.page,
        list_rows: 10,
      }).then((res) => {
        console.log("res.error", res.error);
        if (res.error === 0) {
          this.customersListOptions = [
            ...this.customersListOptions,
            ...res.data.data,
          ];
          if (res.data.current_page < res.data.last_page) {
            this.loadStatus = "加载更多";
            this.noMoreData = false;
            this.page += 1;
          } else {
            this.loadStatus = "没有更多了";
            this.noMoreData = true;
          }
        }
      });
    },
    get_address() {
      Ajax.address({
        promotionId: this.promotionId,
        institution_uuid: this.institution_uuid,
      }).then((res) => {
        if (res.error === 0) {
          this.addressOptions = res.data;
        }
      });
    },
    getPopupContainer(triggerNode) {
      return triggerNode.parentNode;
    },
    handlePopupScroll(value) {
      const { scrollHeight, scrollTop, clientHeight } = value.target;
      if (scrollHeight - scrollTop === clientHeight && !this.noMoreData) {
        this.get_customersList(this.page);
      }
    },
    async handleSelectChange(value) {
      // 找到所选的达人信息

      const selectedUser = this.customersListOptions.find(
        (user) => user.id === value
      );
      if (selectedUser) {
        this.promotionId = selectedUser.ks_user_id;
        this.form.ks_user_id = selectedUser.ks_user_id;
        this.form2.promotionId = selectedUser.ks_user_id;
        this.institution_uuid =
          this.getUserInfo.userLinkInstitution.institution_uuid;
        this.form.institution_uuid =
          this.getUserInfo.userLinkInstitution.institution_uuid;
        this.form2.institution_uuid =
          this.getUserInfo.userLinkInstitution.institution_uuid;
        this.get_address();
      } else {
        console.log("未找到对应的达人");
      }
    },
    addressChange(value) {
      console.log("addressChange", this.form.address_id);
      // this.form.address_id = value;
    },
    get_goodsList() {
        
      if (this.good_ID) {
        
        Ajax.goodsList(this.good_ID).then((res) => {
          if (res.error === 0) {
            this.product_info = res.data;
          }
        });
      }else if(this.detailsInfo.goods_id){
        Ajax.goodsList(this.detailsInfo.goods_id).then((res) => {
          if (res.error === 0) {
            this.product_info = res.data;
          }
        });
      }
      
    },
    samplesAdd() {
      Ajax.samplesAdd(this.form).then((res) => {
        if (res.error === 0) {
          this.$message.success(res.msg);
          this.handleModalCancel();
        }
      });
    },
    addAddress() {
      this.visibleAddress = true;
    },
    handleOkAddress() {
      this.$refs.form2.validate((valid) => {
        if (valid) {

          // 发送请求添加收货地址
          Ajax.add_address(this.form2).then((res) => {
            if (res.error === 0) {
              this.$message.success('收货地址添加成功');
              // 刷新收货地址列表
              this.get_address();
              this.handleModalCancelAddress()
            }
          });
        } else {
          console.log('表单校验失败');
        }
      });
    },
    handleModalCancelAddress() {
      this.visibleAddress = false;
      //清空表单数据
      this.form2 = {
        consignee: '',
        mobile: '',
        province_name: '',
        city_name: '',
        district_name: '',
        address: '',
        defaultArea: [],
        is_default: false,
        promotionId: null,
        institution_uuid: null,
      };
    },
    //选择地区之后的回调
    selectArea(selectedValues) {
      console.log("selectedValues", selectedValues);

      const [provinceId, cityId, districtId] = selectedValues;

      const province = this.areaData.find(prov => prov.code === provinceId);
      this.form2.province_name = province ? province.name : '';
      this.form2.province_id = provinceId;

      if (province) {
        const city = province.children?.find(city => city.code === cityId);
        this.form2.city_name = city ? city.name : '';
        this.form2.city_id = cityId;

        if (city) {
          const district = city.children?.find(district => district.code === districtId);
          this.form2.district_name = district ? district.name : '';
          this.form2.district_id = districtId;
        } else {
          this.form2.district_name = '';
          this.form2.district_id = '';
        }
      } else {
        this.form2.city_name = '';
        this.form2.district_name = '';
        this.form2.city_id = '';
        this.form2.district_id = '';
      }
      this.form2.region = this.form2.province_name +'-'+ this.form2.city_name +'-'+ this.form2.district_name;
      console.log("this.form2", this.form2);
    }

   
  },
  mounted() {
    this.get_customersList();
  },
  watch: {
    detailsInfo: {
      immediate: true,
      handler(newVal) {
        console.log("detailsInfo changed:", newVal);
        
        this.form.apply_commission_rate = newVal.commission_rate;
        this.form.apply_service_rate = newVal.promotion_rate;
        this.form.promotion_money_rate = newVal.promotion_money_complete_rate;
        this.form.task_uuid = this.task_uuid;
        this.good_ID = newVal.id;
        console.log("this.good_NO", newVal.goods_no);
        console.log("this.good_ID", newVal.goods_id);
        if (newVal.goods_no) {
          this.form.goods_no = newVal.goods_no;
        } else {
          this.form.goods_no = newVal.goods_id;
          this.form.apply_service_rate = newVal.open_commission;
          this.form.promotion_money_rate = newVal.open_service_charge;
        }
        console.log(this.form);
        
        if (Object.keys(newVal).length > 0) {
          // 处理 detailsInfo 的变化
          this.get_goodsList();
        }
      },
    },
    addressOptions(newOptions) {
      if (newOptions.length > 0) {
        this.form.address_id = newOptions[0].id;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.table-wrap {
  margin-top: 20px;
  padding-top: 16px;
}

.btn-gruop {
  display: flex;
  justify-content: flex-end;
}

::v-deep .ant-form-item {
  &:last-child {
    margin-bottom: 0;
  }
}
::v-deep .ant-input-number-input {
  text-align: center !important;
}
::v-deep .address_box .ant-select-selection--single {
  position: relative;
  height: 64px;
  cursor: pointer;
}

.tips_box {
  padding: 4px;
}
.text {
  // font-size: 16px;
  color: #999999;
  margin: 10px 0;
  // text-align: center;
  span {
    color: #e33b35;
  }
}
.sale {
  display: flex;
  align-items: center;
  margin-left: 4px;
  margin-bottom: 10px;
  div {
    font-size: 14px;
    span {
      color: #e33b35;
    }
  }
}
.product_information {
  display: flex;
  img {
    width: 110px;
    height: 110px;
    border-radius: 8px;
    margin-right: 10px;
  }
  .product_info {
    .product_name {
      font-weight: 400;
      font-size: 15px;
      color: #666666;
      display: -webkit-box;
      line-height: 21px;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .product_price {
      P {
        font-weight: 600;
        font-size: 12px;
        color: #e33b35;
        margin-bottom: 8px;
        span:nth-child(2) {
          font-size: 18px;
        }
      }
      p:nth-child(2) {
        font-weight: 400;
        font-size: 15px;
        color: #666666;
        line-height: 21px;
      }
    }
  }
}
.input_box {
  display: flex;
  align-items: center;
  .minus_btn {
    width: 30px;
    height: 32px;
    border-radius: 6px 0px 0px 6px;
    border-top: 1px solid #cbcbcb;
    border-left: 1px solid #cbcbcb;
    border-bottom: 1px solid #cbcbcb;
    text-align: center;
    line-height: 30px;
    cursor: pointer;
  }
  .add_btn {
    width: 30px;
    height: 32px;
    border-radius: 0px 6px 6px 0px;
    border-top: 1px solid #cbcbcb;
    border-right: 1px solid #cbcbcb;
    border-bottom: 1px solid #cbcbcb;
    text-align: center;
    line-height: 30px;
    cursor: pointer;
  }
}
.nickname {
  display: inline-block;
  max-width: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 10px;
}
.delivery_rate {
  margin-left: 10px;
  display: inline-block;
  color: #e33b35;
  border-radius: 4px;
  font-size: 12px;
}
.address_btn {
  width: 96px;
  height: 32px;
  background: #f1f8ff;
  border-radius: 4px;
  text-align: center;
  font-weight: 400;
  font-size: 15px;
  color: #1890ff;
  line-height: 32px;
  cursor: pointer;
  margin-left: 14px;
}
.link_box {
  .link_item {
    display: flex;
    align-items: center;
    margin-right: 10px;
  }
  img {
    width: 16px;
    height: 16px;
    cursor: pointer;
  }
  .link_desc {
    font-size: 12px;
    color: #666666;
    margin-top: 4px;
  }
}
.tips_content {
  margin-left: 102px;
  font-weight: 400;
  font-size: 13px;
  color: #e33b35;
}
</style>